package org.graduation.IM.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.graduation.IM.service.GroupMessageService;
import org.graduation.IM.service.socket.SocketService;
import org.graduation.model.common.IM.GroupMessage;
import org.graduation.model.common.ResponseResult;
import org.graduation.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/IM/group_message")
@Slf4j
public class GroupMessageController {
    @Autowired
    private GroupMessageService groupMessageService;
    @Autowired
    private SocketService socketService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Token tokenTool;
    private final static String REDIS_KEY = "group_message:";

    @PostMapping("/send")
    public ResponseResult<GroupMessage> sendMessage(@RequestBody GroupMessage message, @RequestHeader("Authorization") String tokenStr) {
        message.setFromUid(tokenTool.getUidByToken(tokenStr));
        socketService.sendGroupMessage(message);
        return ResponseResult.success(message);
    }

    @GetMapping("/history/{groupId}/{page}/{size}")
    public ResponseResult<List<GroupMessage>> history(@RequestHeader("Authorization") String tokenStr, @PathVariable Long groupId, @PathVariable Integer page, @PathVariable Integer size) {
        Integer uid = tokenTool.getUidByToken(tokenStr);
        List<GroupMessage> result = redisTemplate.opsForList().range(getRedisKey(groupId), (page - 1) * size, page * size);
        if (!(result == null || result.isEmpty())) {
            // 缓存有数据
            return ResponseResult.success(result);
        }
        //缓存没数据
        Page<GroupMessage> page_ = new Page<>(page, size);
        LambdaQueryWrapper<GroupMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(GroupMessage::getGroupId, groupId);
        groupMessageService.page(page_, queryWrapper);
        return ResponseResult.success(page_.getRecords());
    }

    private String getRedisKey(Long groupId) {
        return REDIS_KEY + groupId + ":";
    }
}
